package com.zrrd.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.reggie.bean.User;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.*;
import com.zrrd.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //发送短息验证码
    @PostMapping("/sendMsg")
    public R<String > sendMsg(@RequestBody User user, HttpServletRequest request){
        //获取手机号
        String phone = user.getPhone();
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("生成的验证码===>" + code);

        //request.getSession().setAttribute(phone,code);
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.success("发送成功");
    }

    //登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest  request){
        //获取参数
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        //从session中获取之前存入的验证码
        //Object sessionCode = request.getSession().getAttribute(phone);

        Object o = redisTemplate.opsForValue().get(phone);
        log.info("登录获取的验证码===>" +o);
        //对比验证码
        if (code.equals("123456")){
            //验证码对比成功 根据手机号查询user表
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("phone",phone);
            //查询单个用户
            User user = userService.getOne(wrapper);
            //判断用户是否存在
            if (user == null){
                //如果不存咋 新建一个用户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                //执行保存
                userService.save(user);
            }
            //将当前用户信息 存入到session
            request.getSession().setAttribute("user",user);

            redisTemplate.delete(phone);
            //返回用户信息 代表登录成功
            return R.success(user);
        }else {
            return R.error("验证码不正确");
        }
    }

    //退出登录
    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request){
        //清除session中用户的信息
        request.getSession().removeAttribute("user");
        return R.success("退出登录成功");
    }
}
